package com.panshi.service.impl;

import com.panshi.dao.IRoleDao;
import com.panshi.dao.ISysUserDao;
import com.panshi.service.ISysUserService;
import com.panshi.vo.PagingVO;
import com.panshi.vo.ResultVO;
import com.panshi.vo.SysUserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class SysUserServiceImpl implements ISysUserService{

    @Resource
    private ISysUserDao iSysUserDao;

    @Resource
    private IRoleDao iRoleDao;

    @Override
    public ResultVO<List<SysUserVO>> findSysUserList(PagingVO<?> pagingVO) {
        pagingVO.setBeginNum(pagingVO.getStartNum());
        ResultVO<List<SysUserVO>> resultVO = new ResultVO<>();
        resultVO.setData(iSysUserDao.findSysUserList(pagingVO));
        resultVO.setCount(iSysUserDao.findSysUserCount());
        return resultVO;
    }

    @Override
    public void editSysUserStatus(SysUserVO sysUserVO) {
        iSysUserDao.editSysUserStatus(sysUserVO.getId(),sysUserVO.getStatus());
    }

    @Override
    public ResultVO<String> insertSysUserInfo(SysUserVO sysUserVO) {
        // 根据用户名查询表中是否存在该昵称
        SysUserVO sv = iSysUserDao.getSysUserName(sysUserVO.getName());
        ResultVO<String> resultVO = new ResultVO<>();
        log.info("判断用户是否存在----->{}",sv);
        if(sv == null){
            // 获取新增管管理用户ID
            iSysUserDao.insertSysUserInfo(sysUserVO);
            log.info("新增用户的ID----->{}",sysUserVO.getId());

            // 添加用户角色
            String [] roleIds = sysUserVO.getRoleIds().split(",");
            iSysUserDao.insertSysUserRole(sysUserVO.getId(),roleIds);

            resultVO.setCode("200");
            resultVO.setMsg("新增成功");
        }else{
            resultVO.setCode("A0111");
            resultVO.setMsg("该用户名已存在");
        }
        return resultVO;
    }

    @Override
    public ResultVO<String> delSysUserInfo(long id) {
        ResultVO<String> resultVO = new ResultVO<>();
        // 在数据库中删除该用户
        int SysUserStatus = iSysUserDao.delSysUserInfo(id);
        // 在数据库中删除该用户的角色
        int jurisdictionStatus = iSysUserDao.dleSysUserJurisdiction(id);
        resultVO.setCode("200");
        resultVO.setMsg("已删除");
        return resultVO;
    }

    @Override
    public ResultVO<String> editSysUserInfo(SysUserVO sysUserVO) {
        ResultVO<String> resultVO = new ResultVO<>();
        int status = iSysUserDao.editSysUserInfo(sysUserVO);
        String [] roleIds = sysUserVO.getRoleIds().split(",");
        for (int i = 0; i <roleIds.length ; i++) {
            log.info("角色ID是----{}"+roleIds[i]);
        }
        // 先删除这个用户的权限
        iSysUserDao.dleSysUserJurisdiction(sysUserVO.getId());
        // 修改权限
        iSysUserDao.insertSysUserRole(sysUserVO.getId(),roleIds);
        resultVO.setCode("200");
        return resultVO;
    }


}
